import React from "react";
import { Button, Card, Input, Radio, Typography, message, Space } from "antd";
import { useNavigate, useLocation, Link } from "react-router-dom";
import { useAuth } from "../../contexts/AuthContext";
import type { UserRole } from "../../types/roles";
import { ROUTES } from "../../constants/routes";
import { useForm, Controller } from "react-hook-form";
import { UserOutlined, LockOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';

const { Title } = Typography;

type LoginFormValues = {
    phone: string;
    password: string;
    role: UserRole;
};

const Login: React.FC = () => {
    const { login, loading, user } = useAuth();
    const navigate = useNavigate();
    const location = useLocation() as any;
    const { control, handleSubmit, formState: { errors } } = useForm<LoginFormValues>({
        defaultValues: { role: "patient" },
    });

    React.useEffect(() => {
        if (user) {
            const to = user.role === "doctor" ? ROUTES.doctor.dashboard : ROUTES.patient.dashboard;
            navigate(to, { replace: true });
        }
    }, [user, navigate]);

    // 模拟用手机号登录
    const onSubmit = async (values: LoginFormValues) => {
        try {
            await login({ name: values.phone, role: values.role });
            const target = values.role === "doctor" ? ROUTES.doctor.dashboard : ROUTES.patient.dashboard;
            const from = location?.state?.from?.pathname as string | undefined;
            navigate(from || target, { replace: true });
        } catch {
            message.error("登录失败");
        }
    };

    return (
        <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "#f2f2f7" }}>
            <Card style={{ width: 400 }} className="apple-card login-card">
                <div className="login-header" style={{ textAlign: "center", marginBottom: 32 }}>
                    <Title level={2} style={{ color: "#007aff", marginBottom: 8 }}>医疗系统</Title>
                    <Typography.Text style={{ color: "#8e8e93", fontSize: 16 }}>登录您的账户</Typography.Text>
                </div>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <Space direction="vertical" style={{ width: "100%" }} size="large">
                        <Controller
                            name="phone"
                            control={control}
                            rules={{
                                required: "请输入手机号",
                                pattern: { value: /^1\d{10}$/, message: "请输入11位手机号" },
                            }}
                            render={({ field }) => (
                                <Input 
                                    {...field} 
                                    placeholder="手机号" 
                                    maxLength={11} 
                                    status={errors.phone ? "error" : ""} 
                                    className="apple-input"
                                    prefix={<UserOutlined />}
                                />
                            )}
                        />
                        {errors.phone && <span style={{ color: '#ff4d4f' }}>{errors.phone.message}</span>}
                        <Controller
                            name="password"
                            control={control}
                            rules={{ required: "请输入密码" }}
                            render={({ field }) => (
                                <Input.Password 
                                    {...field} 
                                    placeholder="密码" 
                                    status={errors.password ? "error" : ""} 
                                    className="apple-input"
                                    prefix={<LockOutlined />}
                                    iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                                />
                            )}
                        />
                        {errors.password && <span style={{ color: '#ff4d4f' }}>{errors.password.message}</span>}
                        <div style={{ marginBottom: 8 }}>
                            <Typography.Text style={{ display: "block", marginBottom: 8, color: "#666" }}>用户类型</Typography.Text>
                            <Controller
                                name="role"
                                control={control}
                                render={({ field }) => (
                                    <Radio.Group {...field} className="apple-radio-group">
                                        <Radio.Button value="patient" className="apple-radio-button">患者</Radio.Button>
                                        <Radio.Button value="doctor" className="apple-radio-button">医护</Radio.Button>
                                    </Radio.Group>
                                )}
                            />
                        </div>
                        <Button type="primary" htmlType="submit" block loading={loading} className="apple-button-primary">登录</Button>
                        <Link to="/patient/register">
                            <Button type="link" block className="apple-link-button">
                                还没有账号？去注册
                            </Button>
                        </Link>
                    </Space>
                </form>
            </Card>
        </div>
    );
};

export default Login;


